package com.ml4ai.backend.services.mappers;

import com.ml4ai.backend.domain.CrawlTask;
import com.ml4ai.backend.domain.Text;
import com.ml4ai.backend.dto.CrawlTaskDTO;
import com.ml4ai.backend.dto.TextDTO;
import com.ml4ai.backend.repository.CrawlTaskRepo;
import com.ml4ai.backend.repository.TextRepo;
import com.ml4ai.backend.utils.Bean2Bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by leecheng on 2018/10/28.
 */
@Component
public class CrawlTaskMapper extends BaseMapper<CrawlTask, CrawlTaskDTO> {

    @Autowired
    CrawlTaskRepo crawlTaskRepo;

    @Autowired
    TextMapper textMapper;

    @Autowired
    TextRepo textRepo;

    @Override
    public CrawlTask newEntity() {
        return new CrawlTask();
    }

    @Override
    public CrawlTaskDTO newDTO() {
        return new CrawlTaskDTO();
    }

    @Override
    public CrawlTask find(Long id) {
        return crawlTaskRepo.getOne(id);
    }

    @Override
    public void entity2dto(CrawlTask entity, CrawlTaskDTO dto) {
        new Bean2Bean().addExcludeProp("seeds", "regex").copyProperties(entity, dto);
        if (entity.getSeeds() != null) {
            List<TextDTO> seeds = entity.getSeeds().stream().map(textMapper::e2d).collect(Collectors.toList());
            dto.setSeeds(seeds);
        }
        if (entity.getRegex() != null) {
            List<TextDTO> regex = entity.getRegex().stream().map(textMapper::e2d).collect(Collectors.toList());
            dto.setRegex(regex);
        }
    }

    @Override
    public void dto2entity(CrawlTaskDTO dto, CrawlTask entity) {
        new Bean2Bean().addExcludeProp("seeds", "regex").copyProperties(dto, entity);
        if (dto.getSeeds() != null) {
            List<Text> seeds = dto.getSeeds().stream().map(textMapper::d2e).collect(Collectors.toList());
            entity.setSeeds(seeds);
        }
        if (dto.getRegex() != null) {
            List<Text> regex = dto.getRegex().stream().map(textMapper::d2e).collect(Collectors.toList());
            entity.setRegex(regex);
        }
    }
}
